import JSONEditorComponent from "@/components/JSONEditorComponent";
import { store } from "@/store";
import { Button, Card, Input, message, Segmented, Spin } from "antd";
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";

export default function Debug() {
  const [httpMethod, setHttpMethod] = useState("");
  const [url, setUrl] = useState("");
  const [reqOValue, setReqOValue] = useState("");
  const [bodyData, setBodyData] = useState<any>({ json: {} });
  const [queryData, setQueryData] = useState<any>({ json: {} });
  const [headersData, setHeadersData] = useState<any>({ json: {} });
  const [reqJson, setReqJson] = useState<any>({});
  const [resJson, setResJson] = useState<any>({});
  const [status, setStatus] = useState<number>(0);
  const [loading, setLoading] = useState(false);
  const location = useLocation();
  const handleSend = () => {
    const aC = {
      method: httpMethod.toLowerCase(),
      headers: reqJson.headers,
      data: httpMethod.toLowerCase() == "get" ? undefined : reqJson.body,
      params: reqJson.query,
    };
    setLoading(true);
    setTimeout(() => {
      axios(`${store.extraUrl}${url}`, aC)
        .then((res) => {
          const status = res?.status;
          if (res && status) {
            setStatus(status);
            setResJson(res);
          }
          setLoading(false);
        })
        .catch((err) => {
          const res = err?.response;
          const status = err?.response?.status;
          if (res && status) {
            setStatus(status);
            setResJson(res);
          }
          setLoading(false);
        });
    }, 100);
  };
  useEffect(() => {
    const m = store.apiObj?.methods?.toUpperCase();
    setUrl(store.apiObj.url);
    setHttpMethod(m == "ALL" ? "GET" : m || "GET");
    setReqOValue(m == "POST" ? "body" : "query");
  }, [store.apiObj]);
  useEffect(() => {
    try {
      const a = bodyData.json || JSON.parse(bodyData.text || "{}");
      const b = queryData.json || JSON.parse(queryData.text || "{}");
      const c = headersData.json || JSON.parse(headersData.text || "{}");
      const r = {
        headers: c,
        query: b,
        body: a,
      };

      setReqJson(r);
    } catch (error) {
      // #
    }
  }, [bodyData, queryData, headersData]);
  const timer = useRef<any>(null);
  useEffect(() => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      window.localStorage.setItem(
        `${store.apiObj.url}#_reqJson`,
        JSON.stringify(reqJson)
      );
      window.localStorage.setItem(
        `${store.apiObj.url}#_resJson`,
        JSON.stringify(resJson)
      );
    }, 100);
  }, [reqJson, resJson]);
  useEffect(() => {
    // console.log(store.apiObj.url);
    let nreq: any = window.localStorage.getItem(`${store.apiObj.url}#_reqJson`);
    const nres = window.localStorage.getItem(`${store.apiObj.url}#_resJson`);
    try {
      // console.log(nreq, nres);
      if (nreq) {
        nreq = JSON.parse(nreq);
        setBodyData({ json: nreq.body });
        setHeadersData({ json: nreq.headers });
        setQueryData({ json: nreq.query });
      } else {
        setBodyData({ json: {} });
        setHeadersData({ json: {} });
        setQueryData({ json: {} });
      }
      if (nres) {
        setResJson(JSON.parse(nres));
      } else {
        setResJson({});
      }
    } catch (error) {
      console.log(error);
    }
  }, [store.apiObj]);

  const reqInput: any = {
    body: bodyData,
    headers: headersData,
    query: queryData,
  };
  const reqSet: any = {
    body: setBodyData,
    headers: setHeadersData,
    query: setQueryData,
  };
  const statusColor: any = {
    400: "#ffec3d",
    200: "rgb(23, 178, 106)",
    500: "red",
  };
  const docHttpMethods = store.apiObj?.methods || "";
  return (
    <>
      <div className="flex flex-y-c flex-x-sb">
        <div>
          <Segmented<string>
            options={["GET", "POST"]}
            value={httpMethod}
            onChange={(value) => {
              setHttpMethod(value);
            }}
            disabled={loading}
          />
          <Input
            className="w-4x ml-1"
            value={url}
            disabled={loading}
            onChange={(e) => setUrl(e.target.value)}
          ></Input>
          <Button
            className="ml-1"
            type="primary"
            onClick={() => handleSend()}
            loading={loading}
          >
            发送
          </Button>
        </div>
      </div>
      <div className="flex w-100-pct">
        <Card
          className="mt-1 w-50-pct mr-1m"
          title={
            <div className="flex flex-x-sb flex-y-c">
              <div className="flex flex-y-c">
                <div className="mr-1">请求数据</div>
                <Segmented<string>
                  options={["headers", "query", "body"]}
                  value={reqOValue}
                  onChange={(value) => {
                    setReqOValue(value);
                  }}
                />
              </div>
              <div>
                <Button
                  type="link"
                  size="small"
                  loading={loading}
                  disabled={(() => {
                    if (
                      docHttpMethods.toUpperCase() == "GET" &&
                      reqOValue == "query"
                    ) {
                      return false;
                    }
                    if (
                      docHttpMethods.toUpperCase() == "POST" &&
                      reqOValue == "body"
                    ) {
                      return false;
                    }
                    return true;
                  })()}
                  onClick={() => {
                    const ex = store.apiObj.example;
                    if (!ex) {
                      message.destroy();
                      message.warning("没有响应示例，请联系后端人员~");
                      return;
                    }
                    reqSet[reqOValue]?.({ json: ex });
                  }}
                >
                  一键导入
                </Button>
                <Button
                  type="link"
                  size="small"
                  loading={loading}
                  onClick={() => reqSet[reqOValue]?.({ json: {} })}
                >
                  清除
                </Button>
              </div>
            </div>
          }
          size="small"
        >
          {loading && (
            <>
              <div
                className="abs w-100-pct h-100-pct"
                style={{ zIndex: 9, opacity: 0.5, backgroundColor: "#fff" }}
              ></div>
              <Spin
                className="abs top-50-pct left-50-pct translate--50-pct"
                style={{ zIndex: 10 }}
              />
            </>
          )}

          <JSONEditorComponent
            content={reqInput[reqOValue] || { json: {} }}
            readOnly={false}
            onChange={(obj: any) => {
              reqSet[reqOValue]?.(obj);
            }}
            height={450}
          />
        </Card>
        <Card
          title={
            <div className="flex flex-x-sb flex-y-c">
              <div>调试结果</div>
              {status != 0 && (
                <div
                  className="font-700 font-18px"
                  style={{ color: statusColor[status as any] || "red" }}
                >
                  {status}
                </div>
              )}
            </div>
          }
          className="mt-1 w-50-pct ml-1m"
          size="small"
        >
          {loading && (
            <>
              <div
                className="abs w-100-pct h-100-pct"
                style={{ zIndex: 9, opacity: 0.5, backgroundColor: "#fff" }}
              ></div>
              <Spin
                className="abs top-50-pct left-50-pct translate--50-pct"
                style={{ zIndex: 10 }}
              />
            </>
          )}
          <JSONEditorComponent
            navigationBar={false}
            content={{ json: resJson?.data || {} }}
            height={450}
            readOnly={true}
          />
        </Card>
      </div>
      <div className="flex w-100-pct">
        <Card
          title={
            <div className="flex flex-x-sb flex-y-c">
              <div>请求</div>
            </div>
          }
          className="mt-1 w-50-pct mr-1m"
          size="small"
        >
          {loading && (
            <>
              <div
                className="abs w-100-pct h-100-pct"
                style={{ zIndex: 9, opacity: 0.5, backgroundColor: "#fff" }}
              ></div>
              <Spin
                className="abs top-50-pct left-50-pct translate--50-pct"
                style={{ zIndex: 10 }}
              />
            </>
          )}
          <JSONEditorComponent
            navigationBar={false}
            content={{ json: reqJson }}
            readOnly={true}
          />
        </Card>
        <Card
          title={
            <div className="flex flex-x-sb flex-y-c">
              <div>详细结果</div>
            </div>
          }
          className="mt-1 w-50-pct ml-1m"
          size="small"
        >
          {loading && (
            <>
              <div
                className="abs w-100-pct h-100-pct"
                style={{ zIndex: 9, opacity: 0.5, backgroundColor: "#fff" }}
              ></div>
              <Spin
                className="abs top-50-pct left-50-pct translate--50-pct"
                style={{ zIndex: 10 }}
              />
            </>
          )}
          <JSONEditorComponent
            navigationBar={false}
            content={{ json: resJson || {} }}
            readOnly={true}
          />
        </Card>
      </div>
    </>
  );
}
